package com.syl.ippool.graspimpl;

import com.syl.ippool.domain.IpBasePojo;
import com.syl.ippool.ifice.grasp.IGrasp;
import com.syl.ippool.statics.CommonStatic;
import com.syl.ippool.utils.HttpClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 98免费http代理
 *
 * 官网：http://www.89ip.cn/api.html
 * html网页：http://www.89ip.cn/index_1.html
 * 接口API：http://www.89ip.cn/tqdl.html?api=1&num=30&port=&address=&isp=
 *
 */
public class JiuBaDailiGrasp implements IGrasp {

    private String url = "http://www.89ip.cn/index_%s.html";
    private String name = "98免费http代理";

    private int searchPageNum = 5;

    @Override
    public String getUrl() {
        return url;
    }

    @Override
    public String getWebsiteName() {
        return name;
    }

    @Override
    public List<IpBasePojo> execute() {
        ArrayList<IpBasePojo> resList = new ArrayList<>();

        for (int i = 1; i <= searchPageNum; i++) {
            String result = HttpClientUtils.doGet(String.format(url,i), new HashMap<String, String>(), CommonStatic.computerUserAgent);
            if (StringUtils.isBlank(result)) {
                return null;
            }

            Document doc = Jsoup.parse(result);
            Elements select = doc.select("tbody").select("tr");
            for (Element element : select) {

                try {
                    String ip = element.select("td").get(0).text();
                    String port = element.select("td").get(1).text();
                    String area = element.select("td").get(2).text();

                    IpBasePojo ipBasePojo = new IpBasePojo();
                    ipBasePojo.setIp(ip);
                    ipBasePojo.setPort(Integer.parseInt(port));
                    ipBasePojo.setGetDate(new Date());
                    ipBasePojo.setRegion(area);

                    resList.add(ipBasePojo);
                } catch (Exception e) {
                    // e.printStackTrace();
                }
            }
        }

        return resList;
    }
}
